<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\model;

use buwang\base\BaseModel;
use buwang\util\Util;

/**角色表
 * Class BwAuthNode
 * @package app\manage\model
 */
class AuthGroup extends BaseModel
{
    protected $pk = 'id';

    protected $updateTime = '';

    protected $deleteTime = '';

    /*
* 设置查询初始化条件
* @param string $alias 表别名
* @param object $model 模型实例化对象
* @return object
* */
    public static function valiWhere($alias = '', $model = null)
    {
        $model = is_null($model) ? new self() : $model;
        if ($alias) {
            $model = $model->alias($alias);
            $alias .= '.';
        }
        // return  $model->where("{$alias}delete_time", 0);
        return $model;
    }

    /**得到用户的角色和子孙角色
     * @param $uid
     */
    public static function get_groups($groupids)
    {
        $groupidss = array();
        //得到有效的角色
        $groups = self::where('id', 'in', $groupids)->where('status', 1)->column('id');
        foreach ($groups as $group) {
            //查询所有的有效子权限
            $groupids = self::where('pid', '=', $group)->where('status', 1)->column('id');
            if ($groupids) {
                $groupidsss = self::get_groups($groupids);
                $groupidss = array_merge($groupidsss, $groupidss);
            }

            $groupidss[] = $group;
        }
        return $groupidss;
    }

    /**
     * 获取应用功能套餐
     * @param $where
     * @param int $pid
     * @param $self
     * @return array
     */
    public static function getAppMeal($where, $checked_ids = [], int $pid = 0, $self = null): array
    {
        $self = self::where($where)->order('sort desc,id desc');
        if ($pid) $self = $self->where('pid', $pid);
        //查询所有的分类
        $category = $self->select()->toArray();

        if (!$category) return [];
        //组装API需要的数据 20230512
        $base = $tools = [];
        $group_name = $where['app_name'] . '_base';
        foreach ($category as $obj) {
            if (!empty($checked_ids)) {
                $obj['checked'] = in_array($obj['id'], $checked_ids);
            } else {
                $obj['checked'] = false;
            }
            if ($obj['group_name'] == $group_name) {
                $base[] = [
                    'id' => $obj['id'],
                    'name' => $obj['name'],
                    'en_name' => $obj['group_name'],
                    'introduce' => $obj['name'],
                    'icon' => "https://ossn.buwangkeji.com/upload/20210601/014e09a3dd6a263e685af785df22d83f.png",
                    'status' => $obj['status'],
                    'is_required' => true,
                    'checked' => $obj['checked']
                ];
            } else {
                $tools[] = [
                    'id' => $obj['id'],
                    'name' => $obj['name'],
                    'en_name' => $obj['group_name'],
                    'introduce' => $obj['name'],
                    'icon' => "https://ossn.buwangkeji.com/upload/20210601/014e09a3dd6a263e685af785df22d83f.png",
                    'status' => $obj['status'],
                    'is_required' => false,
                    'checked' => $obj['checked']
                ];
            }

        }
        return compact('base', 'tools');
    }

    /**
     * 得到需要的数组件
     */
    public static function getTree($where, $pid = 0, $checked_ids = [], $disabled = true, $is_child = false, $self = null)
    {
        $data = array();
        if (!$self) $self = new self;
        $self = $self->where($where)->order('sort desc,id desc')->field(['id', 'pid', 'name as label']);
        if ($pid) $self = $self->where('pid', $pid);
        //查询所有的分类
        $category = $self->select()->toArray();
        if (!$category) return $data;
        if ($checked_ids) {
            if (is_array($checked_ids) || is_string($checked_ids) || is_int($checked_ids)) {
                if (is_int($checked_ids)) $checked_ids = [$checked_ids];
                if (is_string($checked_ids)) $checked_ids = explode(',', $checked_ids);//字符串分割数组

            } else {
                $checked_ids = [];
            }

        }

        if (is_array($disabled) || is_string($disabled) || is_int($disabled)) {
            if (is_int($disabled)) $disabled = [$disabled];
            if (is_string($disabled)) $disabled = explode(',', $disabled);//字符串分割数组
        }

        foreach ($category as &$obj) {
            //是否默认选中
            if ($checked_ids) {
                //只有子节点可以被选中
                if ($is_child) {
                    $count = self::where('pid', $obj['id'])->count();
                    if (!$count) {
                        if (in_array($obj['id'], $checked_ids)) $obj['checked'] = true;
                    }
                } else {
                    if (in_array($obj['id'], $checked_ids)) $obj['checked'] = true;
                }
            }

            if (is_array($disabled)) {
                if (in_array($obj['id'], $disabled)) $obj['disabled'] = true;
            } elseif ($disabled === true) {
                //顶级节点禁止选
                if ($obj['pid'] == 0) $obj['disabled'] = true;
            } elseif ($disabled === false) {
                //非顶级节点禁止选
                if ($obj['pid'] != 0) $obj['disabled'] = true;
            }

        }
        $data = Util::tree($category, 'id', 'pid', 'children');
        return $data;
    }


    /**
     * 校验应用角色节点是否重叠
     */
    public static function checkGroupNodes($ids = [])
    {
        $groupNodes = [];
        //得到所有应用跟节点
        $top_nodes = AuthNode::where('pid', 0)->where('type', 'app')->column('id');
        if (count($ids) > 1) {
            foreach ($ids as $id) {
                //得到所有角色对应的节点id
                $nodes = AuthGroupNode::where('group_id', $id)->column('node_id');
                if ($nodes) $groupNodes[] = $nodes;
            }
        }
        if (!$groupNodes) return true;
        //判断是否存在相同节点
        $result = sizeof($groupNodes) > 1 ? array_intersect(...$groupNodes) : $groupNodes[0];
        //如果重复的只是应用根节点则允许重复（安装会过滤掉）
        $result = array_diff($result, $top_nodes);
        if ($result) {
            $result = implode(",", $result);
            return self::setError("选中的角色中，节点[ {$result} ] 重复，请检查去除角色中的重复节点");
        }
        return true;
    }


}
